﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace sy2_12
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private double GetPacket(ref double total, int n)
        {
            if (n == 1)
            {
                return total;
            }
            Random rnd = new Random();
            double avg, thisPacket;
            avg = Math.Round(total / n, 2);
            thisPacket = avg / 2 + avg * rnd.Next(101) / 100;
            thisPacket = Math.Round(thisPacket, 2);
            total -= thisPacket;
            total = Math.Round(total, 2);
            return thisPacket;
        }

        // 计算红包总和的方法
        private double SumPacket(double[] redPackets)
        {
            double sum = 0;
            foreach (double packet in redPackets)
            {
                sum += packet;
            }
            return sum;
        }

        // 假设添加了一个“分发红包”按钮，双击该按钮生成此事件处理方法
        private void btnDistribute_Click(object sender, EventArgs e)
        {
            // 从文本框获取总金额和红包个数（需确保文本框命名为 txtTotal 和 txtCount）
            if (double.TryParse(txtTotal.Text, out double totalAmount) && int.TryParse(txtCount.Text, out int packetCount))
            {
                double total = totalAmount;
                double[] redPackets = new double[packetCount];

                for (int i = packetCount; i > 0; i--)
                {
                    redPackets[packetCount - i] = GetPacket(ref total, i);
                }

                // 显示每个红包金额（需确保多行文本框命名为 txtPackets）
                txtPackets.Text = string.Join(Environment.NewLine, redPackets);
                // 显示红包总和
                double sum = SumPacket(redPackets);
                txtSum.Text = sum.ToString();
            }
            else
            {
                MessageBox.Show("请输入有效的总金额和红包个数！");
            }
        }
    }
}
